package service;

import dao.CroMenusDao;
import entity.CroMenus;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vo.ShowMenuVo;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuweijie on 17-5-6.
 */
@Service
public class CroMenusService {
    @Autowired
    private CroMenusDao croMenusDao;

    /*
    * 根据parentId查出所有的菜单（包含父菜单和子菜单）
    * **/
    @Transactional(readOnly = true)
    public List<CroMenus> FindMenus(String parentId){
        String hql="from CroMenus where parentId=?";
        List<CroMenus> showMenusList = croMenusDao.findList(hql,parentId);
        return showMenusList;
    }

    /**
     * 根据id查找出菜单
     * */
    @Transactional(readOnly = true)
    public CroMenus FindMenusById(String id){
        CroMenus croMenus=croMenusDao.getById(id);
        return croMenus;
    }

    /*
    * 对菜单进行排序
    * **/
    @Transactional(readOnly = true)
    public List<ShowMenuVo> SortMenu(){
        List<ShowMenuVo> resule = transEntity(FindMenus("0"));
        for(int i=0;i<resule.size();i++){
            String pid=resule.get(i).getId();
            resule.get(i).setItemmenu(transEntity(FindMenus(pid)));
        }
        return resule;
    }

    public List<ShowMenuVo> transEntity(List<CroMenus> lists){
        List<ShowMenuVo> resuleList = new ArrayList<>();
        for(int i=0;i<lists.size();i++) {
            ShowMenuVo smo = new ShowMenuVo();
            CroMenus cm = lists.get(i);
            smo.setId(cm.getId());
            smo.setMenuname(cm.getMenuname());
            smo.setParentId(cm.getParentId());
            smo.setUrl(cm.getUrl());
            resuleList.add(smo);
        }
        return resuleList;
    }

    /*
    * 批量添加菜单
    * */
    @Transactional(readOnly = false)
    public Boolean addMenus(List<CroMenus> croMenus){
        try {
            croMenusDao.save(croMenus);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 更新菜单
     * */
    @Transactional(readOnly = false)
    public Boolean updateMenu(CroMenus croMenus){
        try {
            croMenusDao.update(croMenus);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据id删除菜单
     * */
    @Transactional(readOnly = false)
    public Boolean delMenuById(String id){
        if(croMenusDao.findByProperty("parentId",id).size()<=0){
            try{
                croMenusDao.delete(id);
                return true;
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
}
